import SerachKeyWord from "./comps/SerachKeyWord";
import SelectAreaBrand from "./comps/SelectAreaBrand";
import SelectAreaSupp from "./comps/SelectAreaSupp";
import SortComps from "./comps/SortComps";
import GoodsLists from "./comps/GoodsLists";
import GoodsBigItem from "./comps/GoodsBigItem";
import Category from "./comps/Category";
import AgencyLevel from "./comps/AgencyLevel";
import Specification from "./comps/Specification";
import HttpUtils from "../common/utils/HttpUtils";
import CommonUtils from "../common/utils/CommonUtils";
import EventEmitterUtils from "../common/utils/EventEmitterUtils";
import Pagination from "@ui/RJMart/pagination";
import Loading from "@ui/RJMart/loading";
import "./searchproduct.css";
import EventApi from "@module/EventApi";
import ic_notfound from "@assets/ic_notfound.png";

class SearchProduct extends React.Component {
    constructor(props) {
        super(props);
        const params = $state.params;
        let {
            key,
            brandName,
            casNo,
            suppName,
            minPrice,
            maxPrice,
            catId,
            cateFlag,
            catName,
            suppId,
            id
        } = params;

        if (!catId && id) {
            catId = id;
        }

        this.state = {
            key: key || "",
            brand: brandName || "", //选择某个品牌
            supp: suppName || "",
            category: catName || "",
            casNo: casNo || "",
            minPrice: minPrice || "",
            maxPrice: maxPrice || "",
            brandIds: [],
            suppIds: suppId ? [suppId] : [],
            categoryIds: catId ? [catId] : [],
            searchAfter: null,
            city: "",
            sort: "",
            lists_style: 2,
            searchResult: null,
            pageNo: 1,
            cateFlag: cateFlag //catFlag==false，表示前端分页显示10页
        };
        // console.log(this.state.cateFlag)
    }

    componentDidMount() {
        this.searchProducts();
    }

    componentWillUpdate() {
        let hash = window.location.hash;

        if (hash != this.hash) {
            const params = $state.params;

            const {
                key,
                brandName,
                casNo,
                suppName,
                minPrice,
                maxPrice,
                catId,
                cateFlag,
                suppId,
                catName
            } = params;
            this.setState(
                {
                    key: key || "",
                    brand: brandName || "", //选择某个品牌
                    supp: suppName || "",
                    category: catName || "",
                    casNo: casNo || "",
                    minPrice: minPrice || "",
                    maxPrice: maxPrice || "",
                    brandIds: [],
                    suppIds: suppId ? [suppId] : [],
                    categoryIds: catId ? [catId] : [],
                    cateFlag,
                    level: "",
                    levelIds:[],
                    pageNo: 1,
                    specification: "",
                    specificationIds:[],
                },
                this.searchProducts
            );
        }
    }

    searchProducts() {
        const {
            key,
            brand,
            supp,
            casNo,
            minPrice,
            maxPrice,
            suppIds,
            brandIds,
            searchAfter,
            city,
            sort,
            categoryIds,
            pageNo,
            levelIds,
            specificationIds
        } = this.state;
        let searchKeyword = key;
        HttpUtils.searchProducts(
            searchKeyword,
            supp,
            brand,
            casNo,
            minPrice,
            maxPrice,
            suppIds,
            brandIds,
            searchAfter,
            city,
            sort,
            categoryIds,
            pageNo,
            levelIds,
            specificationIds
        )
            .then(res => {
                if (res.code == "0000") {
                    this.setState({
                        searchResult: res
                    });
                }
            })
            .catch(err => {
                console.log(err);
            });
    }

    //分页，下一页
    paginationChange(page) {
        this.setState(
            {
                pageNo: page
            },
            this.searchProducts
        );
    }

    render() {
        this.hash = window.location.hash;
        let {
            brand,
            supp,
            lists_style,
            searchResult,
            key,
            category,
            level,
            specification
        } = this.state;
        if (!searchResult) {
            return (
                <div
                    style={{
                        backgroundColor: "#fff",
                        position: "relative",
                        height: 300
                    }}
                />
            );
        }

        let { brands, supps, products, total } = searchResult; //后台返回的品牌列表

        return (
            <div style={{ backgroundColor: "#fff", position: "relative" }}>
                <div className={"search-page-content-warpper"}>
                    <div className={"search-page-content-box"}>
                        <SerachKeyWord
                            keyword={key}
                            brand={brand}
                            supp={supp}
                            category={category}
                            level={level}
                            specification={specification}
                            closeBrand={() => {
                                this.setState(
                                    {
                                        brand: "",
                                        brandIds: []
                                    },
                                    this.searchProducts
                                );
                            }}
                            closeSupp={() => {
                                this.setState(
                                    {
                                        supp: "",
                                        suppIds: []
                                    },
                                    this.searchProducts
                                );
                            }}
                            closeCategory={() => {
                                this.setState(
                                    {
                                        category: "",
                                        categoryIds: []
                                    },
                                    this.searchProducts
                                );
                                EventApi.emit("searchItemClick", { key: "" });
                            }}
                            closeLevel={() => {
                                this.setState(
                                    {
                                        level: "",
                                        levelIds: []
                                    },
                                    this.searchProducts
                                );
                            }}
                            closeSpecification={() => {
                                this.setState(
                                    {
                                        specification: "",
                                        specificationIds: []
                                    },
                                    this.searchProducts
                                );
                            }}
                        />
                        {this.renderSelectArea()}

                        <SortComps
                            total={total}
                            lists_style={lists_style}
                            setStyle={lists_style => {
                                this.setState(
                                    {
                                        lists_style
                                    },
                                    this.searchProducts
                                );
                            }}
                            setSortword={sort => {
                                this.setState(
                                    {
                                        sort
                                    },
                                    this.searchProducts
                                );
                            }}
                            setCity={city => {
                                this.setState(
                                    {
                                        city
                                    },
                                    this.searchProducts
                                );
                            }}
                            setPrice={(minPrice, maxPrice) => {
                                this.setState(
                                    {
                                        minPrice,
                                        maxPrice
                                    },
                                    this.searchProducts
                                );
                            }}
                        />

                        {this.renderList()}

                        {products && products.length == 0
                            ? this.renderEmity()
                            : this.renderPagination(total)}
                    </div>
                </div>

                <div className={"search-page-footer-top-line"} />
            </div>
        );
    }

    renderEmity() {
        const { lists_style } = this.state;
        return (
            <div
                className={
                    lists_style == 1
                        ? "search-not-fount-product"
                        : "search-not-fount-product2"
                }
            >
                <img src={ic_notfound} alt="" />
                <div style={{ height: 25 }} />
                <p style={{ color: "rgba(150, 150, 150, 1)", fontSize: 13 }}>
                    抱歉，沒有找到相关的宝贝
                </p>
            </div>
        );
    }

    renderPagination(total) {
        let _total = this.getPaginationTotal(total);
        return (
            <div className={"footer-pagination"}>
                <Pagination
                    pageSize={20}
                    total={_total}
                    current={this.state.pageNo}
                    onChange={page => this.paginationChange(page)}
                />
            </div>
        );
    }

    getPaginationTotal(total) {
        if (this.state.cateFlag == "true") {
            return total;
        } else {
            if (total > 200) {
                total = 200;
            }
            return total;
        }
    }

    renderSelectArea() {
        let {
            brand,
            supp,
            category,
            level,
            specification,
            lists_style,
            searchResult,
            key
        } = this.state;
        let {
            brands,
            supps,
            products,
            total,
            categoryIds,
            levels,
            specifications
        } = searchResult;

        if (!searchResult) {
            return null;
        }
        if (
            categoryIds.length == 0 &&
            levels.length == 0 &&
            specifications.length == 0 &&
            brands.length == 0 &&
            supps.length == 0
        ) {
            return null;
        }

        if (
            !brand ||
            !supp ||
            !category ||
            (levels && levels.length > 0 && !level) ||
            !specification
        ) {
            return (
                <div className={"search-page-select-area"}>
                    {!category && categoryIds && categoryIds.length > 0 && (
                        <Category
                            categoryIds={categoryIds}
                            setCategory={(category, categoryIds) => {
                                this.setState(
                                    {
                                        category,
                                        categoryIds,
                                        pageNo: 1
                                    },
                                    this.searchProducts
                                );
                                //     function() {
                                $state.params.catId = categoryIds[0];
                                $state.params.catName = category;

                                // $state.go({
                                //     name: "/searchProduct",
                                //     params: $state.params,
                                //     reload: true
                                // });
                                //     }
                                // );
                                // console.log(category);
                                EventApi.emit("searchItemClick", {
                                    key: category
                                });
                            }}
                        />
                    )}

                    {!brand && brands && brands.length > 0 && (
                        <SelectAreaBrand
                            brandList={brands}
                            supp={supp}
                            brand={brand}
                            setBrand={(brand, brandIds) => {
                                this.setState(
                                    {
                                        brand,
                                        brandIds,
                                        pageNo: 1
                                    },
                                    this.searchProducts
                                );
                            }}
                            searchProducts={() => this.searchProducts()}
                        />
                    )}
                    {!supp && supps && supps.length > 0 && (
                        <SelectAreaSupp
                            suppsList={supps}
                            supp={supp}
                            setSupp={(supp, suppIds) => {
                                this.setState(
                                    {
                                        supp,
                                        suppIds,
                                        pageNo: 1
                                    },
                                    this.searchProducts
                                );
                            }}
                            searchProducts={() => this.searchProducts()}
                        />
                    )}
                    {!level && levels && levels.length > 0 && (
                        <AgencyLevel
                            levels={levels}
                            setLeavel={(level, levelIds) => {
                                this.setState(
                                    {
                                        level,
                                        levelIds,
                                        pageNo: 1
                                    },
                                    this.searchProducts
                                );
                            }}
                        />
                    )}
                    {!specification &&
                        specifications &&
                        specifications.length > 0 && (
                            <Specification
                                specifications={specifications}
                                setSpecification={(
                                    specification,
                                    specificationIds
                                ) => {
                                    this.setState(
                                        {
                                            specification,
                                            specificationIds,
                                            pageNo: 1
                                        },
                                        this.searchProducts
                                    );
                                }}
                            />
                        )}
                </div>
            );
        }
        return null;
    }

    renderList() {
        const { lists_style, searchResult } = this.state;
        const { products } = searchResult;

        if (lists_style == 1) {
            return (
                <div className={"search-page-pro-big-list"}>
                    {products &&
                        products.map((item, index) => (
                            <GoodsBigItem
                                key={index}
                                index={index}
                                item={item}
                            />
                        ))}
                </div>
            );
        }
        return (
            <div>
                {products &&
                    products.map((item, index) => (
                        <GoodsLists key={index} index={index} item={item} />
                    ))}
            </div>
        );
    }
}

export default SearchProduct;

// ReactDOM.render(<SearchProduct/>,document.getElementById('reactRoot'))
